package com.txf.simple.utils;

import android.text.TextUtils;

import java.io.File;
import java.text.DecimalFormat;

/**
 * @author txf
 * @Title
 * @package com.zhsj.tvbee.android.util
 * @date 2016/8/30 0030
 */
public class FileUtils {

    /**
     * 获取文件夹大小
     *
     * @param file File实例
     * @return long
     */
    public static long getFolderSize(File file) {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i].isDirectory()) {
                    size += getFolderSize(fileList[i]);
                } else {
                    size += fileList[i].length();

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    public static String FormetFileSize(long fileS) {//转换文件大小
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = "0\u0020M";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "\u0020K";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "\u0020M";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "\u0020G";
        }
        return fileSizeString;
    }

    /**
     * 删除指定目录下文件及目录
     *
     * @param filePath
     * @param deleteThisPath
     * @param deletefiles
     * @return
     */
    public static void deleteFolderFile(String filePath, boolean deleteThisPath, boolean deletefiles) {
        if (!TextUtils.isEmpty(filePath)) {
            try {
                File file = new File(filePath);
                if (file.isDirectory()) {// 处理目录
                    File files[] = file.listFiles();
                    for (int i = 0; i < files.length; i++) {
                        deleteFolderFile(files[i].getAbsolutePath(), true, deletefiles);
                    }
                }
                if (deleteThisPath) {
                    if (!file.isDirectory()) {// 如果是文件，删除
                        file.delete();
                    } else if (deletefiles) {// 目录
                        if (file.listFiles().length == 0) {// 目录下没有文件或者目录，删除
                            file.delete();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 创建新的文件夹
     * */
    public static boolean createNewFile(File file) {
        if (!file.exists()) {
            try {
                file.createNewFile();
                return true;
            } catch (Exception e) {
                return false;
            }
        }else{

        }
        return true;
    }


}
